package com.uw.uwconfig.client.config;

import com.uw.uwconfig.client.repository.ConfigCacheHolder;
import com.uw.uwconfig.client.repository.UwRepository;
import com.uw.uwconfig.client.repository.UwRepositoryChangeListener;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ConfigVersionChecker {

    private final Map<String, Long> versionMap = new HashMap<>();

    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    private final ConfigServerMeta meta;

    private final UwRepository uwRepository;


    public ConfigVersionChecker(ConfigServerMeta meta, UwRepository uwRepository) {
        this.meta = meta;
        this.uwRepository = uwRepository;
    }

    public void start() {
        executor.scheduleWithFixedDelay(() -> {
            try {

                Long newVersion = uwRepository.version(meta);
                Long curVersion = versionMap.getOrDefault(meta.key(), -1L);

                // 表明服务端配置存在更新
                if (curVersion < newVersion) {
                    log.info("[UwConfig] >> ConfigVersionChecker current={}, newVersion={}", curVersion, newVersion);
                    Map<String, Object> localConfigs = uwRepository.getConfig(meta);
                    Map<String, Object> newConfig = uwRepository.getConfigWithoutCache(meta);

                    Map<String, Object> changedConfig = ConfigCacheHolder.compare(localConfigs, newConfig);

                    UwRepositoryChangeListener.ChangeEvent changeEvent = new UwRepositoryChangeListener.ChangeEvent(meta, changedConfig);
                    versionMap.put(meta.key(), newVersion);
                    uwRepository.onChange(changeEvent);
                }
            } catch (Exception ex) {
                log.error("[UwConfig] >> ConfigVersionChecker error", ex);
            }
        }, 1, 3, TimeUnit.SECONDS);
    }

    public void stop() {
        executor.shutdown();
    }
}
